<template>
    <div class="menu-list-container">
      <a-card :bordered="false" class="search-card">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="菜单名称">
            <a-input v-model:value="searchForm.menuName" placeholder="请输入菜单名称" />
          </a-form-item>
          <a-form-item label="状态">
            <a-select v-model:value="searchForm.status" placeholder="请选择状态" style="width: 120px">
              <a-select-option value="">全部</a-select-option>
              <a-select-option value="0">启用</a-select-option>
              <a-select-option value="1">禁用</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
            <a-button 
              type="primary" 
              style="margin-left: 8px" 
              @click="showDrawer"
              v-if="hasPermission('system::menu::save')"
            >
              新增
            </a-button>
          </a-form-item>
        </a-form>
      </a-card>
      
      <div class="divider" style="background: #f5f5f5; height: 16px;"></div>
      
      <a-card :bordered="false" class="table-card" :style="{ overflow: 'hidden' }">
        <a-table
          :columns="columns"
          :data-source="dataSource"
          :loading="loading"
          :pagination="false"
          row-key="id"
          :defaultExpandAllRows="true"
          :childrenColumnName="'children'"
          @change="handleTableChange"
          :scroll="{ y: 500 }"
          :style="{ width: '100%' }"
        >
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'index'">
              {{ index + 1 }}
            </template>
            <template v-if="column.key === 'icon'">
              <component 
                :is="validIcons[record.icon]" 
                v-if="record.icon && validIcons[record.icon]"
              />
              <span v-else>-</span>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-switch 
                :checked="record.status === '0'" 
                @change="(checked) => handleStatusChange(record.id, checked)"
                :loading="record.id === statusLoadingId"
                checked-children="启用" 
                un-checked-children="禁用"
              />
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button 
                  type="link" 
                  size="small" 
                  @click="handleEdit(record)"
                  v-if="hasPermission('system::menu::save')"
                >
                  <EditOutlined />
                </a-button>
                <a-button 
                  type="link" 
                  size="small" 
                  danger
                  @click="handleDelete(record)"
                  v-if="hasPermission('system::menu::delete')"
                >
                  <DeleteOutlined />
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
      
      <a-modal
        title="选择图标"
        :open="iconModalVisible"
        @cancel="iconModalVisible = false"
        :footer="null"
        width="1000px"
        :bodyStyle="{ padding: '16px 24px' }"
      >
        <div 
          style="
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 12px;
            max-height: 60vh;
            overflow-y: auto;
          "
        >
          <div 
            v-for="(icon, name) in validIcons" 
            :key="name"
            @click="handleIconClick(name)"
            style="
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              padding: 12px;
              cursor: pointer;
              border-radius: 4px;
              transition: all 0.2s;
              height: 90px;
              border: 1px solid #f0f0f0;
            "
            class="icon-item"
          >
            <component 
              :is="icon" 
              style="
                font-size: 24px;
                margin-bottom: 8px;
                color: rgba(0, 0, 0, 0.85);
              " 
            />
            <span 
              style="
                font-size: 12px;
                text-align: center;
                line-height: 1.4;
                word-break: break-word;
                white-space: pre-wrap;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                overflow: hidden;
              "
            >
              {{ name }}
            </span>
          </div>
        </div>
      </a-modal>
  
      <a-drawer
        title="新增菜单"
        :visible="drawerVisible"
        @close="drawerVisible = false"
        width="800"
      >
        <a-form
          :model="formState"
          layout="vertical"
          :style="{ maxWidth: '800px', padding: '20px' }"
        >
          <!-- 上级菜单 -->
          <a-form-item label="上级菜单">
            <a-tree-select
              v-model:value="formState.parentId"
              :tree-data="menuTreeData"
              placeholder="请选择上级菜单"
              :fieldNames="{children: 'children', title: 'title', key: 'id', value: 'id'}"
              show-search
              :tree-default-expand-all="false"
              @change="(value, label, extra) => { formState.parentMenuName = extra?.selectedNodes?.[0]?.title || '' }"
            />
          </a-form-item>
  
          <!-- 菜单类型 -->
          <a-form-item label="菜单类型">
            <a-radio-group v-model:value="formState.menuType" button-style="solid">
              <a-radio-button value="moudule">模块</a-radio-button>
              <a-radio-button value="menu">菜单</a-radio-button>
              <a-radio-button value="button">按钮</a-radio-button>
              <a-radio-button value="iframe">外链</a-radio-button>
            </a-radio-group>
          </a-form-item>
  
          <!-- 菜单图标 -->
          <a-form-item label="菜单图标">
            <a-input
              v-model:value="formState.menuIcon"
              placeholder="点击选择图标"
              @click="handleIconSelect"
            />
          </a-form-item>
  
          <!-- 菜单名称和显示排序 -->
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item
                label="菜单名称"
                name="menuName"
                :rules="[{ required: true, message: '请输入菜单名称' }]"
              >
                <a-input v-model:value="formState.menuName" placeholder="请输入菜单名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="显示排序"
                name="sortOrder"
                :rules="[{ required: true, message: '请输入显示排序' }]"
              >
                <a-input-number
                  v-model:value="formState.sortOrder"
                  style="width: 100%"
                  :min="0"
                />
              </a-form-item>
            </a-col>
          </a-row>
  
          <!-- 是否外链 -->
          <a-form-item label="是否外链">
            <a-radio-group v-model:value="formState.isExternal" button-style="solid">
              <a-radio-button value="yes">是</a-radio-button>
              <a-radio-button value="no">否</a-radio-button>
            </a-radio-group>
          </a-form-item>
  
          <!-- 路由地址 -->
          <a-form-item
            label="路由地址"
            name="routePath"
            :rules="[{ required: true, message: '请输入路由地址' }]"
          >
            <a-input v-model:value="formState.routePath" placeholder="请输入路由地址" />
          </a-form-item>
  
          <!-- 组件路径 -->
          <a-form-item label="组件路径">
            <a-input v-model:value="formState.componentPath" placeholder="请输入组件路径" />
          </a-form-item>
  
          <!-- 权限字符和路由参数 -->
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="权限字符">
                <a-input v-model:value="formState.permission" placeholder="请输入权限标识" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="路由参数">
                <a-input v-model:value="formState.routeParams" placeholder="请输入路由参数" />
              </a-form-item>
            </a-col>
          </a-row>
  
          <!-- 缓存和状态 -->
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="是否缓存">
                <a-radio-group v-model:value="formState.cache" button-style="solid">
                  <a-radio-button value="cache">缓存</a-radio-button>
                  <a-radio-button value="no-cache">不缓存</a-radio-button>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="显示状态">
                <a-radio-group v-model:value="formState.visible" button-style="solid">
                  <a-radio-button value="show">显示</a-radio-button>
                  <a-radio-button value="hide">隐藏</a-radio-button>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>
  
          <!-- 菜单状态 -->
          <a-form-item label="菜单状态">
            <a-radio-group v-model:value="formState.status" button-style="solid">
              <a-radio-button value="normal">正常</a-radio-button>
              <a-radio-button value="disabled">停用</a-radio-button>
            </a-radio-group>
          </a-form-item>
        </a-form>
        <div :style="{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
            zIndex: 1,
          }">
          <a-button style="margin-right: 8px" @click="handleCancel">取消</a-button>
          <a-button type="primary" @click="handleSubmit">确认</a-button>
        </div>
      </a-drawer>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, computed, onMounted } from 'vue';
  import * as allIcons from '@ant-design/icons-vue';
  import { EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import { searchMenuList, updateMenuStatus, deleteMenuInfo, searchAllMenuNode } from '@/api/system/menu';
  import { Modal } from 'ant-design-vue';
  import { hasPermission } from '@/utils/permission.js';
  
  // 图标处理
  const validIcons = computed(() => {
    return Object.entries(allIcons).reduce((acc, [name, component]) => {
      if (
        (typeof component === 'object' && component.render) ||
        typeof component === 'function'
      ) {
        acc[name] = component;
      }
      return acc;
    }, {});
  });
  
  // 表格列配置
  const columns = [
    {
      title: '菜单名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '菜单标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '菜单编码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '组件路径',
      dataIndex: 'component',
      key: 'component',
    },
    {
      title: '权限标识',
      dataIndex: 'perms',
      key: 'perms',
    },
    {
      title: '菜单图标',
      dataIndex: 'icon',
      key: 'icon',
    },
    {
      title: '菜单备注',
      dataIndex: 'remark',
      key: 'remark',
    },
    {
      title: '状态',
      key: 'status',
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
    },
  ];
  
  // 数据状态
  const dataSource = ref([]);
  const loading = ref(false);
  const statusLoadingId = ref(null);
  const drawerVisible = ref(false);
  const iconModalVisible = ref(false);
  const menuTreeData = ref([]);
  const searchForm = reactive({
    menuName: null,
    status: null,
  });
  const formState = reactive({
    id: null,
    parentId: null,
    menuType: 'moudule',
    menuIcon: '',
    menuName: '',
    sortOrder: 0,
    isExternal: 'no',
    routePath: '',
    componentPath: '',
    permission: '',
    routeParams: '',
    cache: 'cache',
    visible: 'show',
    status: 'normal'
  });
  
  // 方法
  const fetchMenuTree = async () => {
    try {
      const res = await searchAllMenuNode({ id: -1 });
      menuTreeData.value = res.menuInfoTree;
    } catch (error) {
      console.error(error);
    }
  };
  
  const fetchData = async () => {
    try {
      loading.value = true;
      const res = await searchMenuList();
      dataSource.value = res;
    } catch (error) {
      console.error(error);
    } finally {
      loading.value = false;
    }
  };
  
  const handleSearch = () => {
    fetchData();
  };
  
  const resetSearch = () => {
    Object.assign(searchForm, {
      menuName: null,
      status: null
    });
    handleSearch();
  };
  
  const handleStatusChange = async (id, checked) => {
    try {
      statusLoadingId.value = id;
      await updateMenuStatus({ id });
      fetchData();
    } catch (error) {
      console.error(error);
    } finally {
      statusLoadingId.value = null;
    }
  };
  
  const showDrawer = async () => {
    drawerVisible.value = true;
    await fetchMenuTree();
    if(menuTreeData.value.length > 0) {
      formState.parentId = menuTreeData.value[0].id;
    }
  };
  
  const handleIconSelect = () => {
    iconModalVisible.value = true;
  };
  
  const handleIconClick = (iconName) => {
    formState.menuIcon = iconName;
    iconModalVisible.value = false;
  };
  
  const handleEdit = (record) => {
    console.log('Edit:', record);
    // 实现编辑逻辑
  };
  
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除菜单【${record.name}】吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteMenuInfo({ id: record.id });
          fetchData();
        } catch (error) {
          console.error(error);
        }
      },
    });
  };
  
  const handleCancel = () => {
    drawerVisible.value = false;
  };
  
  const handleSubmit = () => {
    // 实现提交逻辑
    drawerVisible.value = false;
  };
  
  onMounted(() => {
    fetchData();
  });
  </script>
  
  <style scoped>
  .menu-list-container {
    padding: 0px;
  }
  .search-card {
    margin-bottom: 0px;
  }
  .table-card {
    margin-bottom: 0px;
  }
  
  :deep(.ant-table-body) {
    overflow-y: auto !important;
  }
  
  .icon-item:hover {
    background-color: #f5f5f5;
    border-color: #d9d9d9;
  }
  </style>